export class ListNode {
    val: number;
    next: ListNode | null;
    constructor(val?: number, next?: ListNode | null) {
        this.val = val === undefined ? 0 : val;
        this.next = next === undefined ? null : next;
    }

    toString() {
        console.log(`[ListNode] val:${this.val}`);
    }
}

/**
 * 数组转链表
 */
export function array2list(arr: number[]): ListNode {
    if (!arr || arr.length <= 0) return new ListNode();

    let head = new ListNode(arr[0]);
    let last = head;
    for (let i = 1; i < arr.length; i++) {
        const item = new ListNode(arr[i]);
        last.next = item;
        last = item;
    }
    return head;
}

export function list2array(head: ListNode | null): number[] {
    const result: number[] = [];
    while (head) {
        result.push(head.val);
        head = head.next;
    }
    return result;
}

export class TreeNode {
    val: number;
    left: TreeNode | null;
    right: TreeNode | null;
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = val === undefined ? 0 : val;
        this.left = left === undefined ? null : left;
        this.right = right === undefined ? null : right;
    }
}
